<template>
  <el-tabs v-model="activeName" class="demo-tabs">
    <el-tab-pane label="密码" name="password">
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入账号">
            <template #prefix>
              <el-icon class="el-input__icon">
                <user />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password
            autocomplete="new-password">
            <template #prefix>
              <el-icon class="el-input__icon">
                <lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <!-- 拖动验证 -->
          <dragVerify v-model:value="isPassing"></dragVerify>
          <div class="login-tips">
            <el-checkbox v-model="checked">记住密码</el-checkbox>
            <el-button link type="primary">忘记密码?</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-tab-pane>
    <el-tab-pane label="短信" name="shortMessage">
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入手机号">
            <template #prefix>
              <el-icon class="el-input__icon">
                <user />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input clearable v-model="loginForm.password" placeholder="验证码" :prefix-icon="WarnTriangleFilled">
            <template #append>
              发送验证码
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </el-tab-pane>
  </el-tabs>
  <div class="login-btn">
    <el-button :icon="CircleClose" round size="large" @click="resetForm(loginFormRef)"> 重置 </el-button>
    <el-button :icon="UserFilled" round size="large" type="primary" :loading="loading" @click="login(loginFormRef)">
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { ElMessage, ElNotification } from "element-plus";
import { loginApi } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled, WarnTriangleFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import md5 from "md5";
import DragVerify from "@/components/DragVerify/dragVerify.vue";
import { Login } from "@/api/interface";
import { useAuthStore } from "@/stores/modules/auth";
import { Base64 } from 'js-base64'
import Cookies from 'js-cookie'

const activeName = ref('password')
const isPassing = ref(false);

const router = useRouter();
const userStore = useUserStore();
const authStore = useAuthStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  username: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  username: "",
  password: ""
});

const checked = ref(false);

// 登录
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  // 检查验证是否通过
  if (!isPassing.value) {
    ElNotification({
      title: "验证未通过",
      message: "请完成滑动验证",
      type: "warning",
      duration: 3000
    });
    return;
  }

  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      const res = await loginApi({ ...loginForm });
      userStore.setToken(res.token);
      userStore.setSysJobList(res.sysJobList);
      userStore.setFirstJobId(res.sysJobList[0].id);
      userStore.setFirstJobName(res.sysJobList[0].jobName);
      userStore.setUserInfo(res);

      // 设置当前选中的岗位id
      authStore.setCurrentJobId(res.sysJobList[0].id)
      authStore.setCurrentJobList(res.sysJobList);

      // 2.添加动态路由
      await initDynamicRouter();

      // 3.清空 tabs、keepAlive 数据
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);

      // 4.跳转到首页
      router.push(HOME_URL);
      // 获取当前时间
      const now = new Date();
      const hours = now.getHours();

      // 根据当前时间设置问候语
      let greeting: string = '';
      if (hours >= 5 && hours < 12) {
        greeting = '嗨，上午好！';
      } else if (hours >= 12 && hours < 18) {
        greeting = '嗨，下午好！';
      } else if (hours >= 18 && hours < 22) {
        greeting = '嗨，晚上好！';
      } else {
        greeting = '嗨，夜深了，早点休息！';
      }

      ElNotification({
        title: greeting,
        dangerouslyUseHTMLString: true,
        message: "欢迎登录 广千教育系统",
        type: "success",
        duration: 8000
      });

      // 记住密码逻辑
      if (checked.value) {
        const { username, password } = loginForm;
        const localForm = {
          username: Base64.encode(username),
          password: Base64.encode(password),
        };
        Cookies.set('LOCAL_KEY', JSON.stringify(localForm));
      } else {
        Cookies.remove('LOCAL_KEY');
      }
    } catch (error) {
      if (error.response.status === 500) {
        ElMessage.error("登录失败，请联系管理员！");
      } else {
        ElMessage.error("登录失败，请检查账号或密码是否正确!");
      }
    } finally {
      loading.value = false;
    }
  });
};

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };

  // 查询本地是否存了用户名密码
  queryLocalForm();
});

onBeforeUnmount(() => {
  document.onkeydown = null;
});

// 查询本地是否存了用户名密码
const queryLocalForm = () => {
  const localForm = Cookies.get('LOCAL_KEY');
  if (localForm) {
    checked.value = true;
    try {
      const { username, password } = JSON.parse(localForm);
      loginForm.username = Base64.decode(username);
      loginForm.password = Base64.decode(password);
    } catch (error) {
      console.error('本地数据解析失败~', error);
    }
  } else {
    checked.value = false;
  }
};
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
